import { ClickModal, FieldCols, mapField, useCall } from '@/components';
import { LIABILITY_TYPE } from '@/constants/options';
import { enumToOptions, forkHandler } from '@/utils';
import { catchAndScrollFor } from '@/utils/fp';
import { Form } from 'antd';
import React from 'react';

const FIELDS = [
  [
    'liabilityCode',
    '责任代码',
    null,
    {
      placeholder: '请输入在以下范围之内的字符 (a~z A~Z 0~9)',
      rules: [
        { required: true, message: '请输入责任代码' },
        {
          pattern: /^[a-zA-Z0-9]+$/,
          message: '责任代码不能包含特殊字符，只能输入以下字符 (a~z A~Z 0~9)',
        },
      ],
    },
  ],
  ['liabilityName', '责任名称', null, { required: true }],
  [
    'liabilityType',
    '责任属性',
    'radio-group',
    { initialValue: Object.keys(LIABILITY_TYPE)[0], options: enumToOptions(LIABILITY_TYPE) },
  ],
  [
    'liabilityDesc',
    '责任描述',
    'textarea',
    {
      colProps: { xs: 24 },
      itemProps: {
        labelCol: { span: 4 },
        wrapperCol: { span: 20 },
      },
    },
  ],
].map(mapField);

function LiabilityEditModal({ item, onOk, onToggle, index, ...props }) {
  const [form] = Form.useForm();

  const handleToggle = useCall(
    forkHandler(onToggle, (visi) => {
      if (visi) item ? form.setFieldsValue(item) : form.resetFields();
    }),
  );

  const handleOk = useCall(async () => {
    const values = await form.validateFields().catch(catchAndScrollFor(form));
    return onOk?.(values);
  });

  const content = (
    <Form form={form}>
      <FieldCols form={form} fields={FIELDS} colProps={{ xs: 12 }} />
    </Form>
  );

  return <ClickModal {...props} content={content} onOk={handleOk} onToggle={handleToggle} />;
}

export default LiabilityEditModal;
